$(function () {
	
	var flag;
	
    $.post("GetBooksByPageServlet",function(data,status) {
    	console.log($("#cusrname").text());
    	if($("#cusrname").text()=="请登录"){
     	  aa="aaa1254";
        }else{
          aa="asd111";
        }
    	
        var booksInfo=data;
        $( booksInfo.list).each(function (index,elem) {
            $("#Books").append("<li><dl><dd><a href='BookDetail.jsp?bookId="+elem.BookId+"&aa="+aa+"'><img class='imgHover' src='"+elem.Picture+"' width='100px' height='154px' alt='"+elem.BookId+"' /></a>chuan</dd><dt><p class='book_title'><a href='#' target='_blank'>"+elem.BookName+"</a></p><p class='book_inline'>Price:$"+elem.Price+"</p><a onclick='addToCart("+elem.BookId+")' class='book_addToCart' href='javascript:void(0)'>ADD TO CART</a><br/><br/><a class='book_buy' href='InsertOrderByBookIdServlet?bookId="+elem.BookId+"'>BUY</a></dt></dl></li>");
        })
        for (var i=0;i<booksInfo.totilPages;i++){
            var index=i+1;
            $("#bookPage").append("<button href='javascript:void(0)' onclick='setCurrentPage("+index+")' class='bookPageNum' style=''>"+index+"</button>");
        }
        
       if(aa=="aaa1254"){
    	 $(".book_addToCart").attr('href',"javascript:void(0);");
    	 $(".book_addToCart").click(function(){
    		 alert("Please Login firstly!");
    	 });
    	 $(".book_buy").attr('href',"javascript:void(0);");
    	 $(".book_buy").click(function(){
    		 alert("Please Login firstly!");
    	 });
       }
    },"json");

    // Get cart info before this
    
    $.ajax({
    	url: 'CountGoodsInCartServlet',
    	type: 'POST',
    	success: function(response) {
    		$('#itemCount').text(response);
    	}
    });

    // Bind Navbar buttons OnClick Event
    $('#btnShoppingCart').click(function(){
    	window.location.href="cart.jsp";
    });

    $('#btnMyOrder').click(function(){
    	window.location.href="MyOrder.jsp";
    });

    $('#btnSignout').click(function () {
        window.location.href="login.jsp";
    });
})

function setCurrentPage(index) {
    $.post("SetCurrentPageServlet",{currentPage:index},function (data,status) {
        window.location.reload();
    })
}

function addToCart(BookId){
	$.ajax({
		data:{
			"bookId":BookId,
			"quantity":"1"
		},
		type:"post",
		url:"AddCartServlet",
		success:function(response){
			if(response=="success")
			{
				alert("Addition succeeded!");
			}
			else{
				alert("Addition failed!");
			}
			
			$.ajax({
		    	url: 'CountGoodsInCartServlet',
		    	type: 'POST',
		    	success: function(response) {
		    		$('#itemCount').text(response);
		    	}
		    });
		}
	});
}



